<script setup>
  import { reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { loginAPI } from '@/api/user.js'
  import useUserStore from '@/stores/user'

  const router = useRouter()
  const userStore = useUserStore()

  const form = reactive({
    username: '管理员',
    password: '123456'
  })
  let submitting = ref(false)

  function handleLogin() {
    if (submitting.value) return
    if (!form.username || !form.password) {
      return ElMessage.error('账号或密码未填写')
    }
    submitting.value = true
    loginAPI(form)
      .then(res => {
        let userInfo = {
          token: res.api_token,
          isSuper: res.is_super == 1 ? true : false,
          name: res.name,
          id: res.id,
          avatar: res.photo,
          roles: res.roles,
          permissions: res.role_list
        }
        userStore.setUserInfo(userInfo)
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
        router.replace('/')
      })
      .finally(() => submitting.value = false)
  }
</script>

<template>
  <div class="main flex justify-content-c align-items-c">
    <div class="form-container">
      <h2>后台管理系统</h2>
      <el-form :model="form" size="large">
        <el-form-item label="账号">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="submitting" native-type="submit" type="primary" size="large" style="width: 100%;"
            @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
  .main {
    width: 100%;
    height: 100vh;
    background-image: url('../assets/images/bg.jpg');
    background-size: inherit inherit;
  }

  .form-container {
    width: 420px;
    background: #FFF;
    padding: 30px 30px 30px;
    border: 1px solid #CDD0D6;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
</style>